package cn.edu.nenu.model.controller;

import com.ibm.jpa.web.JPAManager;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import com.ibm.jpa.web.Action;
import cn.edu.nenu.model.Employee;

@JPAManager(targetEntity = cn.edu.nenu.model.Employee.class)
public class EmployeeManager {

	private EntityManagerFactory emf;

	public EmployeeManager() {
	
	}

	public EmployeeManager(EntityManagerFactory emf) {
		this.emf = emf;
	}

	public void setEntityManagerFactory(EntityManagerFactory emf) {
		this.emf = emf;
	}

	private EntityManager getEntityManager() {
		if (emf == null) {
			throw new RuntimeException(
					"The EntityManagerFactory is null.  This must be passed in to the constructor or set using the setEntityManagerFactory() method.");
		}
		return emf.createEntityManager();
	}

	@Action(Action.ACTION_TYPE.CREATE)
	public String createEmployee(Employee employee) throws Exception {
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			em.persist(employee);
			em.getTransaction().commit();
		} catch (Exception ex) {
			try {
				if (em.getTransaction().isActive()) {
					em.getTransaction().rollback();
				}
			} catch (Exception e) {
				ex.printStackTrace();
				throw e;
			}
			throw ex;
		} finally {
			em.close();
		}
		return "";
	}

	@Action(Action.ACTION_TYPE.DELETE)
	public String deleteEmployee(Employee employee) throws Exception {
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			employee = em.merge(employee);
			em.remove(employee);
			em.getTransaction().commit();
		} catch (Exception ex) {
			try {
				if (em.getTransaction().isActive()) {
					em.getTransaction().rollback();
				}
			} catch (Exception e) {
				ex.printStackTrace();
				throw e;
			}
			throw ex;
		} finally {
			em.close();
		}
		return "";
	}

	@Action(Action.ACTION_TYPE.UPDATE)
	public String updateEmployee(Employee employee) throws Exception {
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			employee = em.merge(employee);
			em.getTransaction().commit();
		} catch (Exception ex) {
			try {
				if (em.getTransaction().isActive()) {
					em.getTransaction().rollback();
				}
			} catch (Exception e) {
				ex.printStackTrace();
				throw e;
			}
			throw ex;
		} finally {
			em.close();
		}
		return "";
	}

	@Action(Action.ACTION_TYPE.FIND)
	public Employee findEmployeeByEmployeeId(int employeeId) {
		Employee employee = null;
		EntityManager em = getEntityManager();
		try {
			employee = (Employee) em.find(Employee.class, employeeId);
		} finally {
			em.close();
		}
		return employee;
	}

	@Action(Action.ACTION_TYPE.NEW)
	public Employee getNewEmployee() {
	
		Employee employee = new Employee();
	
		return employee;
	}

}